﻿using System;
using System.Collections.Generic;
using Entities;
using Microsoft.AspNetCore.Mvc;
using Portal.Models;
using SqlSugar;
using WMS.DtoModels;

namespace Portal.Controllers
{
    /// <summary>
    /// 角色管理业务逻辑
    /// </summary>
    public class RoleController : Controller
    {
        private readonly SqlSugarClient _sqlSugarClient;

        public RoleController(SqlSugarClient sqlSugarClient)
        {
            _sqlSugarClient = sqlSugarClient;
        }

        /// <summary>
        /// 加载所有的角色
        /// </summary>
        /// <param name="roleInfoReqDto"></param>
        /// <returns></returns>
        public IActionResult LoadAllRole(RoleInfoReqDto roleInfoReqDto)
        {
            var totalCount = 0;
            var querySqlQueryable = this._sqlSugarClient.Queryable<sys_role>();

            //querySqlQueryable = querySqlQueryable.Where(new
            //{
            //    Name = roleInfoReqDto.Name,
            //    Available = roleInfoReqDto.Available
            //});

            var queryResult = querySqlQueryable.ToPageList(roleInfoReqDto.Page, roleInfoReqDto.Limit, ref totalCount);


            return Json(new
            {
                Code = 0,
                Msg = "查询成功",
                Count = totalCount,
                Data = queryResult
            });
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="roleInfo"></param>
        /// <returns></returns>
        public IActionResult AddRole(sys_role roleInfo)
        {
            roleInfo.createtime = DateTime.Now;
            var insertNum = this._sqlSugarClient.Insertable<sys_role>(roleInfo).ExecuteCommand();

            var result = new LayUiStandardResDto<object>
            {
                Code = GlobalVariable.Ok,
                Msg = $"成功添加{insertNum}个角色"
            };

            return Json(result);
        }

        /// <summary>
        /// 更新角色信息
        /// </summary>
        /// <param name="roleEntity"></param>
        /// <returns></returns>
        public IActionResult UpdateRole(sys_role roleEntity)
        {
            //查询角色
            var queryRole = this._sqlSugarClient.Queryable<sys_role>().Where(x => x.id == roleEntity.id).First();
            if (queryRole == null)
            {
                var errorResult = new LayUiStandardResDto<object>
                {
                    Code = GlobalVariable.Error,
                    Msg = $"需要更新的角色 {roleEntity.name} 不存在."
                };

                return Json(errorResult);
            }

            queryRole.name = roleEntity.name;
            queryRole.available = roleEntity.available;
            queryRole.createtime = roleEntity.createtime;

            var updateNum = this._sqlSugarClient.Updateable<sys_role>(roleEntity).ExecuteCommand();

            var result = new LayUiStandardResDto<object>
            {
                Code = GlobalVariable.Ok,
                Msg = $"成功更新了{updateNum}个部门信息"
            };

            return Json(result);
        }

        /// <summary>
        /// 删除角色信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult DeleteRole(int id)
        {
            var deleteNum = this._sqlSugarClient.Deleteable<sys_role>().Where(x => x.id == id).ExecuteCommand();

            var result = new LayUiStandardResDto<object>
            {
                Code = GlobalVariable.Ok,
                Msg = $"成功删除了{deleteNum}个部门信息"
            };

            return Json(result);
        }

        /// <summary>
        /// 获取指定角色分配的权限情况
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public IActionResult InitPermissionByRoleId(int roleId)
        {
            //获取指定角色已经拥有的所有权限
            var pids = this._sqlSugarClient.Queryable<sys_role_permission>().Where(x => x.rid == roleId).Select(x => x.pid);
            var queryResult = this._sqlSugarClient.Queryable<sys_permission>().Where(x => pids.ToList().Contains(x.id)).ToList();


            var allPermissionConfig = this._sqlSugarClient.Queryable<sys_permission>().ToList();
            

            var list = new List<DTreeResDto>();

            foreach (var item in allPermissionConfig)
            {
                var temp = queryResult.Find(x => x.id == item.id);


                var curValue = new DTreeResDto
                {
                    Id = item.id,
                    Title = item.title,
                    ParentId = item.pid
                };

                if (temp == null)
                {
                    curValue.CheckArr = 0.ToString();  //标记未选中
                }
                else
                {
                    curValue.CheckArr = 1.ToString();  //标记选中
                }

                list.Add(curValue);
            }

            var result = new LayUiStandardResDto<DTreeResDto>
            {
                Code = 0,
                Msg = "查询成功",
                Data = list
            };

            return Json(result);


        }

        /// <summary>
        /// 为角色分配权限
        /// </summary>
        /// <returns></returns>
        public IActionResult SaveRolePermission(int rid, int[] ids)
        {
            var insertData = new List<sys_role_permission>();

            foreach (var item in ids)
            {
                insertData.Add(new sys_role_permission
                {
                    rid = rid,
                    pid = item
                });
            }


            //TODO:此处应该开启事务,保证业务数据一致性

            //删除之前已经存在的用户角色
            this._sqlSugarClient.Deleteable<sys_role_permission>().Where(x => x.rid == rid).ExecuteCommand();
            this._sqlSugarClient.Insertable<sys_role_permission>(insertData).ExecuteCommand();

            var successResult = new LayUiStandardResDto<object>
            {
                Code = GlobalVariable.Ok,
                Msg = $"权限分配成功."
            };

            return Json(successResult);
        }
    }
}